package model

import (
	"fmt"
	"time"

	"chat.com/pkg/logger"
	"chat.com/setting"

	_ "github.com/jinzhu/gorm/dialects/mysql"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var log *logger.Logger = logger.NewLogger("pkg/logger/model.log", "")

// db for coupon db coupons_ table
var db *gorm.DB
var err error

// Setup initializes the database instance
func Setup() {
	// init db
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True",
		setting.DatabaseSetting.User,
		setting.DatabaseSetting.Password,
		setting.DatabaseSetting.Host,
		setting.DatabaseSetting.Name,
	)

	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{TranslateError: true}, &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix: setting.DatabaseSetting.TablePrefix, // table name prefix, table for `User` would be `t_users`
		},
	})

	if err != nil {
		panic(fmt.Sprintf("modelSetup err: %v", err))
	}

	// Auto migrate user tables
	autoMigrateTables()

	sqlDB, err := db.DB()
	if err != nil {
		panic(fmt.Sprintf("modelSetup err: %v", err))
	}

	//Set max number of connections
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(30 * time.Minute)
}

// Auto migrate table if table does not exist
func autoMigrateTables() {

	tables := []interface{}{
		SingleFriend{},
		SingleMessageSendBox{},
		Group{},
		GroupMember{},
		GroupMessageSendBox{},
		GroupMessageRecieveBox{},
		SysMessageSendBox{},
		SysMessageOffset{},
	}

	for _, t := range tables {
		if ok := db.Migrator().HasTable(&t); !ok {
			db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&t)
		}
	}
}
